class CategoriesController < ApplicationController
  before_filter :check_administrator_role,:except => [:show,:json_for_select,:index]
  #  protect_from_forgery :except => :update
  caches_action :index, :if => Proc.new { |c| c.request.format.json? }

  # GET /categories
  # GET /categories.xml
  before_filter :find_cart
  def index
    @categories = Category.paginate :page => params[:page],:per_page => 15

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @categories }
      format.json { render :text=>build_tree(Category.find(:all,
            :conditions=>'parent_id is null')).to_json}
    end
  end

  # GET /categories/1
  # GET /categories/1.xml
  def show
    @category = Category.find(params[:id])
    if params[:brand_id]
      @sub_category = Category.find_by_parent_and_brand(params[:brand_id],params[:id])
      @brand = Brand.find(params[:brand_id])
      if @category.products.size > 0
        @products = @category.products.paginate :all,:conditions=>["brand_id = ?",params[:brand_id]],
          :page => params[:page],:per_page => 5,:order=>'sort_order desc'
      end
    else
      @category = Category.find(params[:id])
      @sub_category = @category.children
      @brands = Brand.get_all_by_categery(params[:id])

      if @category.products.size > 0
        @products = @category.products.paginate :page => params[:page],:per_page => 5,:order=>'sort_order desc'
      end
    end
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @category }
    end
  end

  # GET /categories/new
  # GET /categories/new.xml
  def new
    @category = Category.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @category }
    end
  end

  # GET /categories/1/edit
  def edit
    @category = Category.find(params[:id])
  end

  # POST /categories
  # POST /categories.xml
  def create
    @category = Category.new(params[:category])

    respond_to do |format|
      if @category.save
        flash[:notice] = 'Category was successfully created.'
        format.html { redirect_to(@category) }
        format.xml  { render :xml => @category, :status => :created, :location => @category }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @category.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /categories/1
  # PUT /categories/1.xml
  def update
    @category = Category.find(params[:id])
    result = @category.update_attributes(params[:category])


    if !request.xhr?
      respond_to do |format|
        if result
          flash[:notice] = 'Category was successfully updated.'
          format.html { redirect_to(@category) }
          format.xml  { head :ok }
        else
          format.html { render :action => "edit" }
          format.xml  { render :xml => @category.errors, :status => :unprocessable_entity }
        end
      end
    else
      if result
        if params[:category][:parent_id] or params[:category][:unit]
          if params[:category][:parent_id]
            render :text=> Category.find(params[:category][:parent_id]).name
          elsif params[:category][:unit]
            unit = Category::UNITS.find{|s|s[1] == params[:category][:unit]}
            render :text=>unit[0]
          end
        else
          render :text=> params[:category].values.to_s
        end
      else
        render :text=>'false'
      end
    end
    
  end

  # DELETE /categories/1
  # DELETE /categories/1.xml
  def destroy
    @category = Category.find(params[:id])
    @category.destroy

    respond_to do |format|
      format.html { redirect_to(categories_url) }
      format.xml  { head :ok }
    end
  end

  def json_for_select
    json_arr = Array.new
    build_json(Category.find(:all,:conditions=>["parent_id is null"]),json_arr)
    return_json = json_arr.join(",")
    return_json = "{" + return_json + "}"
    render :text=>return_json
  end

  def sort_sub_category
    @category = Category.find(params[:id])
    @categories = @category.children
  end

  def sort_product
    if params[:brand_id]
      @brand=Brand.find(params[:brand_id])
      @category = Category.find(params[:id])
      @products = Product.find_all_by_brand_id_and_category_id(params[:brand_id],params[:id],:order=>'sort_order desc')
    else
      @products = Product.find_all_by_category_id(params[:id],:order=>'sort_order')
    end
  end

  def sort_brand
    @category = Category.find(params[:id])
    @brands = Brand.get_all_by_categery(params[:id])
  end

  def update_sort_order
    json_data =JSON::parse(params[:json])
    json_data.each {|i| Category.update(i["id"],:sort_order=>i["order"])}
    render :text => "排序已保存"
  end

  def migrate_product
    new_category_id = params[:new_category_id]
    new_category = Category.find(new_category_id)
    old_category = Category.find(params[:id])

    if new_category_id
      result = Product.update_all(["category_id = ? where category_id = ?",new_category_id,params[:id]])
      Category.update_counters  params[:new_category_id],:products_count=>old_category.products.size
      Category.update_counters  params[:id],:products_count=>-old_category.products.size
    end
    

    respond_to do |format|
      if result
        flash[:notice] = "成功更新#{result}条记录."
        format.html { redirect_to(new_category) }
        format.xml  { head :ok }
      else
        format.html { redirect_to(new_category) }
        format.xml  { render :xml => category.errors, :status => :unprocessable_entity }
      end
    end
    
  end

  private

  def build_json(categories,json_arr)
    categories.each { |c|
      if c.children.size > 0
        json_arr << "'#{c.id}':'#{c.name_for_select}'"
        build_json(c.children,json_arr)
      else
        json_arr << "'#{c.id}':'#{c.name_for_select}'"
      end
    }
  end

  def build_tree(categories)
    data = Array.new
    categories.each { |category|
      if category.children.size > 0
        #        category.children_count = category.children.count
        #        category.save
        tmp_data = [{"text"=>category.name,"id"  => category.id,"cls"=>'file',
            "children" => build_tree(category.children) }]
        if data.empty?
          data =   tmp_data
        else
          data.concat(tmp_data)
        end

      else
        data.concat([{"text" => "<a href='/categories/#{category.id}/products'>#{category.name}(#{category.products.size})</a>","id" => category.id}])
      end

    }
    return data
  end
end
